<template>
  <div>
    <ElRow style="margin-bottom: 16px">
      <el-button v-if="hasPerms('front:product:create')" type="primary" @click="handleAdd">新增</el-button>
    </ElRow>
    <ReTable :data="productList" :columns="columns" :pagination="pagination">
      <template #payType="{ row }">
        {{ payTypeEnums[row.payType] }}
      </template>
      <template #action="{ row }">
        <ElRow justify="center" align="middle">
          <ElCol v-if="hasPerms('front:product:edit')" :span="6">
            <ElButton link type="primary" @click="editRow(row)">
              编辑
            </ElButton>
          </ElCol>
          <ElCol v-if="hasPerms('front:product:status')" :span="6">
            {{ console.log(row) }}
            <ElSwitch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1"
              :inactive-value="0" @change="updateStatus(row)" />
          </ElCol>
        </ElRow>
      </template>
    </ReTable>
    <ElDialog v-model="dialogVisible" :title="dialogTitle" width="680" :close-on-click-modal="false"
      :destroy-on-close="true" align-center>
      <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
        <ElFormItem label="产品名" prop="productName">
          <ElInput v-model="ruleForm.productName" placeholder="请输入产品名" />
        </ElFormItem>
        <ElFormItem label="付费类型" prop="payType">
          <ElRadioGroup v-model="ruleForm.payType">
            <ElRadio :value="0">付费</ElRadio>
            <ElRadio :value="1">免费</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="试卷" prop="paperIds">
          <!--添加按钮带表格展示-->
          <div style="display: flex; flex-flow: column; width: 100%">
            <ElButton style="width: 48px; margin-bottom: 10px" type="primary" @click="addPaper">添加</ElButton>
            <ReTable :data="paperList" height="auto" :columns="paperColumns" :show-index="true" />
          </div>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </ElDialog>
    <ElDialog v-model="paperDialogVisible" title="添加试卷" width="50%" align-center destroy-on-close>
      <div style="display: flex; justify-content: flex-end; margin-bottom: 16px">
        <ElInput v-model="paperKeyword" :prefix-icon="Search" placeholder="试卷编号/试卷名称/归属试卷组"
          style="width: 250px; margin-right: 10px" clearable @change="searchPaper" />
      </div>
      <ReTable ref="paperTableRef" :data="selPaperList" :columns="paperColumns" :pagination="paperPagination"
        :show-selection="true" :selections="ruleForm.paperIds" style="min-height: 200px"
        @current-change="handlePaperCurrentChange" @size-change="handelPaperSizeChange"
        @selection-change="handleSelectionChange" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="paperDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sureAddPaper"> 确定 </el-button>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import ReTable from "@/components/ReTable";
import {
  createProduct,
  getProductList,
  updateProductStatus
} from "@/api/frontend";
import { onMounted } from "vue";
import { ref } from "vue";
import { getPaperList } from "@/api/paper";
import { ElDialog, ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { nextTick } from "vue";
import { hasPerms } from "@/utils/auth";
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "FrontendManage"
});

// 弹窗显示
const dialogVisible = ref(false);
// 弹窗标题
const dialogTitle = ref("新增");
// 表单ref
const ruleFormRef = ref();
// 表单数据
const ruleForm = ref({
  productName: "",
  payType: 0,
  paperIds: []
});
// 表单规则
const rules = ref({
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  payType: [{ required: true, message: "请选择支付类型", trigger: "change" }],
  paperIds: [{ required: true, message: "请选择试卷", trigger: "change" }]
});

// 选择试卷弹窗表格数据
const selPaperList = ref([]);
// 选择试卷搜索关键词
const paperKeyword = ref("");
// 选择试卷弹窗显示
const paperDialogVisible = ref(false);

// 添加试卷表格数据
const paperList = ref([]);
// 试卷表格列配置
const paperColumns = [
  {
    prop: "id",
    label: "试卷编号",
    align: "center"
  },
  {
    prop: "name",
    label: "试卷名称",
    align: "center"
  },
  {
    prop: "groupName",
    label: "归属试卷组",
    align: "center"
  }
];

// 前端产品列表分页参数
const pageParams = ref({
  pageNum: 1,
  pageSize: 10
});

// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
});
// 列配置
const columns = [
  {
    prop: "productCode",
    label: "产品编号",
    align: "center"
  },
  {
    prop: "productName",
    label: "产品名",
    align: "center"
  },
  {
    prop: "payType",
    label: "付费类型",
    align: "center",
    slotName: "payType"
  },
  {
    prop: "gmtModified",
    label: "修改时间",
    align: "center"
  },
  {
    prop: "creator",
    label: "创建人",
    align: "center"
  },
  {
    prop: "action",
    label: "操作",
    slotName: "action"
  }
];

// payType枚举对象 0 付费 1 免费
const payTypeEnums = {
  0: "付费",
  1: "免费"
};

// 前端产品列表数据
const productList = ref([]);
// 获取前端产品列表
const queryProductList = async (params: any) => {
  try {
    const res = await getProductList(params);
    if (res.code === 200) {
      productList.value = res.data.records;
      pagination.value.total = res.data.total;
      console.log(productList.value);
    }
  } catch (error) {
    console.log(error);
  }
};

// 新增产品弹窗显示
const handleAdd = () => {
  // 初始化表单数据
  ruleForm.value = {
    productName: "",
    payType: 0,
    paperIds: []
  };
  paperList.value = [];
  selPaperList.value = [];
  // 显示弹窗
  dialogVisible.value = true;
};

// 确认新增
const submitForm = (formRef: any) => {
  formRef.validate(async (valid: any) => {
    if (valid) {
      try {
        const res = await createProduct(ruleForm.value);
        console.log(res);
        if (res.code === 200) {
          dialogVisible.value = false;
          ElMessage.success("新增成功");
          queryProductList(pageParams.value);
        } else if (res.code === 0) {
          // 操作弹窗提示
          const tipsTxt = ruleForm.value.payType === 0 ? "付费" : "免费";
          ElMessageBox.confirm(
            `已有正在启用的${tipsTxt}产品，确认要切换为当前${tipsTxt}产品?`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          ).then(async () => {
            // 获取列表中得对应类型得产品
            const oldItem = productList.value.find(
              (item: any) =>
                item.payType === ruleForm.value.payType && item.status === 1
            );
            if (oldItem) {
              // 修改状态
              try {
                await updateProductStatus({ id: oldItem.id, status: 0 });
                const ret = await createProduct(ruleForm.value);
                if (ret.code === 200) {
                  dialogVisible.value = false;
                  ElMessage.success("新增成功");
                  queryProductList(pageParams.value);
                } else {
                  ElMessage.error(res.message);
                }
              } catch (error) {
                console.log(error);
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    }
  });
};

// 更新产品状态
const updateStatus = async (row: any) => {
  try {
    const res = await updateProductStatus({ id: row.id, status: row.status });
    if (res.code === 200) {
      ElMessage.success("操作成功");
      queryProductList(pageParams.value);
    } else if (res.code === 0) {
      // 操作弹窗提示
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.log(error);
  }
};

// 编辑产品
const editRow = (row: any) => {
  console.log(row);
  ruleForm.value = {
    productName: row.productName,
    payType: row.payType,
    paperIds: row.papers.map((item: any) => item.id)
  };
  paperList.value = row.papers;
  dialogVisible.value = true;
};

// 添加弹窗
const addPaper = async () => {
  paperPagination.value.pageNum = 1;
  await querySelPaperList();
};

// 查询试卷列表
const pageListParams = ref({
  name: ""
});

// 搜索试卷
const searchPaper = async () => {
  querySelPaperList();
};

// 选择试卷
const handleSelectionChange = (val: any) => {
  console.log(val);
};
const paperPagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const querySelPaperList = async () => {
  try {
    const res = await getPaperList({
      name: paperKeyword.value,
      pageNum: paperPagination.value.pageNum,
      pageSize: paperPagination.value.pageSize
    });
    if (res.code === 200) {
      selPaperList.value = res.data.records;
      paperPagination.value.total = res.data.total;
      // 显示弹窗
      paperDialogVisible.value = true;
      nextTick(() => {
        selPaperList.value.forEach((item: any) => {
          if (ruleForm.value.paperIds.includes(item.id)) {
            paperTableRef.value.tableRef.toggleRowSelection(item, true);
          }
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};

// 分页
const handlePaperCurrentChange = (val: number) => {
  paperPagination.value.pageNum = val;
  querySelPaperList();
};

// 分页大小改变
const handelPaperSizeChange = (val: number) => {
  paperPagination.value.pageSize = val;
  querySelPaperList();
};

// 选择试卷表格ref
const paperTableRef = ref(null);
// 选择试卷
const sureAddPaper = () => {
  // 获取选中行
  const rows = paperTableRef.value.tableRef.getSelectionRows();
  console.log(rows);
  paperList.value = rows;
  ruleForm.value.paperIds = rows.map((item: any) => item.id);
  // 关闭弹窗
  paperDialogVisible.value = false;
};

onMounted(() => {
  queryProductList(pageParams);
});
</script>
